import { Injectable, Inject } from '@nestjs/common';
import type { Pool } from 'mysql2/promise';
import { camelCase, isArray } from 'lodash-es';

const toCamelCaseRow = (row: Record<string, any>) => {
  const result: Record<string, any> = {};
  for (const key in row) {
    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    result[camelCase(key)] = row[key];
  }
  return result;
};

@Injectable()
export class DatabaseService {
  constructor(@Inject('MYSQL_CONNECTION') private readonly pool: Pool) {}

  /**
   * 通用查询方法（带类型提示）
   * @example
   */
  async query<T = any>(sql: string, params?: any[]): Promise<T[]> {
    const [rows] = await this.pool.query(sql, params);
    if (isArray(rows)) {
      return (rows as any[]).map(toCamelCaseRow) as T[];
    } else {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-return
      return toCamelCaseRow(rows) as any;
    }
  }
}
